/*
 *  NFCSigning - Open source library for signing/validation of NDEF messages
 *  Copyright (C) 2009-2010 The NFCSigning Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */
package sampleappa;

//#ifdef MyJSR257
//# import my.javax.microedition.contactless.ndef.NDEFMessage;
//# import my.javax.microedition.contactless.ndef.NDEFRecord;
//# import my.javax.microedition.contactless.ndef.NDEFRecordType;
//#else
import javax.microedition.contactless.ndef.NDEFMessage;
import javax.microedition.contactless.ndef.NDEFRecord;
import javax.microedition.contactless.ndef.NDEFRecordType;
//#endif

/**
 *
 * @author emarkki
 */
public class SmartPosterRecord {
    
    public static final NDEFRecordType RECORD_TYPE = 
            new NDEFRecordType(NDEFRecordType.NFC_FORUM_RTD, "urn:nfc:wkt:Sp");
    
    private NDEFRecord[] records;
    
    public SmartPosterRecord(NDEFRecord[] records) {
        this.records = records;
    }
    
    public SmartPosterRecord(byte[] payload) {
        decode(payload);
    }
    
    public NDEFRecord toNDEFRecord() {
        return new NDEFRecord(RECORD_TYPE, new byte[0], encode(records));
    }
    
    private static byte[] encode(NDEFRecord[] records) {
        NDEFRecord[] ndefRecords = new NDEFRecord[records.length];
        for(int i = 0; i < records.length; i++) {
            ndefRecords[i] = records[i];
        }
        NDEFMessage msg = new NDEFMessage(ndefRecords);
        return msg.toByteArray();
    }
    
    private void decode(byte[] payload) {
        NDEFMessage msg = new NDEFMessage(payload, 0);
        records = msg.getRecords();
    }

    public NDEFRecord[] getRecords() {
        return records;
    }

    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("[Sp");
        for(int i = 0; i < records.length; i++) {
            sb.append(", " + records[i]);
        }
        sb.append("]");
        return sb.toString();
    }
}
